﻿using DG.Tweening;
using Share;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;

namespace UIElement
{

    public delegate void OnNavigateBarClick(int nIndex);

    //广告牌控件, 由多个BannerItem组成，
    //滚动显示，滚动停止时显示当前项，滚动开始时显示下一项，可以点击触发点击事件，
    //分成横向滚动和纵向滚动两种模式，默认为横向滚动，
    // 可以指定滚动速度，以及每一项得停留时间
    // 有点状得导航条，可以点击后，快速切换到某一项
    public class BannerBar : ScrollBase
    {
        public enum EMoveDir
        {
            [Description("从右到左")]
            Right2Left = 1,
            [Description("从左到右")]
            Left2Right = 2,
            [Description("从上到下")]
            Up2Down = 3,
            [Description("从下到上")]
            Down2Up = 4,
        }

        /// <summary>滚动速度</summary>
        [SerializeField] private float scrollSpeed = 0.5f;
        /// <summary>每项停留时间(秒)</summary>
        [SerializeField] private float stayDuration = 3f;

        [SerializeField] private NavigationBar navigationBar;
        /// <summary>导航点实例列表</summary>
        private List<GameObject> dotIndicators = new List<GameObject>();
        /// <summary>当前显示项的索引</summary>
        private int currentIndex = 0;
        /// <summary>停留计时器</summary>
        private SmartTimer stayTimer = new SmartTimer();
        /// <summary>滚动方向，0是不动</summary>
        private bool isScrolling = false;
        /// <summary>是否为横向滚动</summary>
        [SerializeField]
        private EMoveDir moveDir = EMoveDir.Right2Left;


        private CommonListItem currentItem = null;
        private CommonListItem nextItem = null;

        /// <summary>
        /// 边框得宽度
        /// </summary>
        private Vector2 frameSize = Vector2.zero;


        /// <summary>
        /// 初始化组件
        /// </summary>
        private void Awake()
        {
            //switch( moveDir )
            //{
            //    case EMoveDir.Right2Left:
            //    case EMoveDir.Left2Right: //这两个加入横向布局
            //        content.gameObject.AddComponent<HorizontalLayoutGroup>();
            //        break;
            //    case EMoveDir.Up2Down:
            //    case EMoveDir.Down2Up://这两个加入纵向布局
            //        content.gameObject.AddComponent<VerticalLayoutGroup>();
            //        break;
            //}
            frameSize = GetComponent<RectTransform>().sizeDelta;
        }

        protected override void InitItemProfabs()
        {
            if (currentItem != null)
                currentItem.gameObject.StopOrDestroy();
            if (nextItem != null)
                nextItem.gameObject.StopOrDestroy();


            if (m_ItemProfab == null)
            {
                XKLog.LogError("创建广告牌失败, 广告牌模板没有指定");
                return;
            }
            //广告牌需要创建2个元素，用来显示一半的item
            currentItem = CreateBannerItem();
            nextItem = CreateBannerItem();
            nextItem.gameObject.SetActive(false);
        }
        CommonListItem CreateBannerItem()
        {
            var item = ObjectMgr.Instance.CreateObj(m_ItemProfab.gameObject, m_Content.transform);
            if (item == null)
            {
                XKLog.LogError("创建广告牌失败, 广告牌模板配置错误，实例化模板失败");
                return null;
            }
            var banner = item.GetOrAddComponent<CommonListItem>();
            banner.Init(OnSelectItem, OnShowItem);
            return banner;
        }

        public override void DoInit(int count, OnShowDelegate showItemFunc, OnSelectDelegate selctItemFunc)
        {
            base.DoInit(count, showItemFunc, selctItemFunc);
            stayTimer.DoReset(stayDuration);
        }
        private void NavigateBarClick(int nIndex)
        {
            MoveToItem(nIndex);
        }
        /// <summary>
        /// 每帧更新，处理自动滚动逻辑
        /// </summary>
        private void Update()
        {
            // 正在滚动，不计算计时器
            if (isScrolling)
                return;
            //停留时间到，开始滚动
            if (stayTimer.DoUpdate())
            {
                MoveToItem(currentIndex + 1);

            }
            //content.gameObject
        }

        void MoveToItem(int index)
        {
            // 如果当前已经是了，就不管
            if (currentIndex == index)
                return;

            // 往前滚
            bool bForwad = index > currentIndex;

            //首先计算，目标位置怎么滚最近
            if (index >= ItemNum) // 如果超出了，就从0开始
            {
                index = 0;
            }
            if (index < 0)
                index = ItemNum - 1;

            nextItem.SetItemData(index);
            nextItem.gameObject.SetActive(true);

            switch (moveDir)
            {
                case EMoveDir.Down2Up:
                case EMoveDir.Right2Left:
                    break;
                case EMoveDir.Up2Down:
                case EMoveDir.Left2Right:
                    bForwad = !bForwad;
                    break;
            }
            float fEnd = -frameSize.x;
            if (bForwad)
                nextItem.GetComponent<RectTransform>().localPosition = new Vector2(frameSize.x, 0);
            else
            {
                nextItem.GetComponent<RectTransform>().localPosition = new Vector2(-frameSize.x, 0);
                fEnd = frameSize.x;
            }

            //开始滚动
            switch (moveDir)
            {
                case EMoveDir.Down2Up:
                    m_Content.DOMoveY(-frameSize.y, scrollSpeed);
                    break;
                case EMoveDir.Right2Left:
                    m_Content?.DOKill();
                    m_Content.DOLocalMove(new Vector2(fEnd, 0), scrollSpeed).OnComplete(() =>
                    {
                        ExchangeItem();
                        FixCurrentPosition();
                        stayTimer.DoReset();
                        isScrolling = false;
                    });
                    break;
                case EMoveDir.Up2Down:
                    break;
                case EMoveDir.Left2Right:
                    break;
            }
            currentIndex = index;
            if (navigationBar != null)
                navigationBar.MoveToIndex(currentIndex, scrollSpeed);
            isScrolling = true;
        }
        void ExchangeItem()
        {
            var temp = currentItem;
            currentItem = nextItem;
            nextItem = temp;
            nextItem.gameObject.SetActive(false);
        }

        //总共有几个展示牌
        public override void SetCount(int count)
        {
            base.SetCount(count);
            currentIndex = 0;
            currentItem.SetItemData(currentIndex);
            if (navigationBar != null)
            {
                navigationBar.Init(count, NavigateBarClick);
            }
            FixCurrentPosition();
        }


        //刷新当前得位置
        void FixCurrentPosition()
        {
            m_Content.GetComponent<RectTransform>().localPosition = Vector2.zero;
            currentItem.GetComponent<RectTransform>().localPosition = Vector2.zero;
        }

    }
}
